//
//  YJQSportCameraViewController.m
//  GoodLuck
//
//  Created by 杨瑞 on 17/2/20.
//  Copyright © 2017年 杨瑞. All rights reserved.
//

#import "YJQSportCameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

#define YJQCameraPictureDuration 2.0

@interface YJQSportCameraViewController ()
@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *maskViewConstraints;
@property (weak, nonatomic) IBOutlet UIView *previewView;
//ic_waterprint_action_oriented
@property (weak, nonatomic) IBOutlet UILabel *waterprintLabel;
@property (weak, nonatomic) IBOutlet UIImageView *waterprintImage;
/**
 拍照完成提示
 */
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
/**
 拍照按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *captureButton;
/**
 前后镜头/分享按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *rotateShareButton;

@end



@implementation YJQSportCameraViewController {
    /// 拍摄会话
    AVCaptureSession *_captureSession;
    /// 输入设备 - 摄像头
    AVCaptureDeviceInput *_inputDevice;
    /// 图像输出
    AVCaptureStillImageOutput *_imageOutput;
    /// 取景框 - 预览图层
    AVCaptureVideoPreviewLayer *_previewLayer;
    
    /// 拍摄完成的图像
    UIImage *_capturedPicture;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCaptureSession];
    // Do any additional setup after loading the view from its nib.
}

-(BOOL)prefersStatusBarHidden {
    return YES;
}
#pragma mark - capture

/**
 拍照
 */
- (IBAction)capture {
    if (!_captureSession.isRunning) {
        [self rotateButtonsAnimation];
        return;
    }
    [self maskViewAminWithClose:YES];
    [self capturePicture];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(YJQCameraPictureDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self maskViewAminWithClose:NO];
    });
    
}
- (void)maskViewAminWithClose:(BOOL)close {
    if (close) {
        [NSLayoutConstraint deactivateConstraints:_maskViewConstraints];
        
    }else {
        [NSLayoutConstraint activateConstraints:_maskViewConstraints];
        [self rotateButtonsAnimation];
    }
    [UIView animateWithDuration:YJQCameraPictureDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}
/**
 拍照按钮的翻转动画
 */
- (void)rotateButtonsAnimation {
    BOOL emptyTitle = (_captureButton.currentTitle == nil);
    NSString *title = emptyTitle ? @"✓" : nil;
    [_captureButton setTitle:title forState:UIControlStateNormal];
    UIViewAnimationOptions option = emptyTitle ? UIViewAnimationOptionTransitionFlipFromRight : UIViewAnimationOptionTransitionFlipFromLeft;
    [UIView transitionWithView:_captureButton duration:YJQCameraPictureDuration options:option animations:nil
                    completion:^(BOOL finished) {
                        if (title == nil) {
                            [self startCapture];
                        }
                    }];
    NSString *imageName = emptyTitle ? @"ic_waterprint_share" : @"ic_waterprint_revolve";
    [self.rotateShareButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [UIView transitionWithView:self.rotateShareButton duration:YJQCameraPictureDuration options:option animations:nil completion:nil];
}

- (IBAction)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)switchCamera {
    if (!_captureSession.running) {
        [self sharedPicture];
        return;
    }
    AVCaptureDevice *device = [self captureDevice];
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:NULL];
    [self stopCapture];
    [_captureSession removeInput:_inputDevice];
    if ([_captureSession canAddInput:input]) {
        _inputDevice = input;
    }
    [_captureSession addInput:input];
    [self startCapture];
}

/**
 分享照片
 */
- (void)sharedPicture {
    if (_capturedPicture == nil) {
        return;
    }
    //1、创建分享参数
//    NSArray* imageArray = @[[UIImage imageNamed:@"shareImg.png"]];
    NSArray *imageArray = @[_capturedPicture];
//    （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
//    if (imageArray) {
    
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                         images:imageArray
                                            url:nil
                                          title:@"分享标题"
                                           type:SSDKContentTypeAuto];
        //有的平台要客户端分享需要加此方法，例如微博
        [shareParams SSDKEnableUseClientShare];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];
//    }
}

#pragma mark - 相机相关方法
/**
 设置拍摄会话
 */
- (void)setupCaptureSession {
    // 0. 具体的设备 - 摄像头／麦克风(模拟器没有摄像头，应该使用真机测试)
    AVCaptureDevice *device = [self captureDevice];
    // 1. 输入设备 - 可以添加到拍摄会话
    _inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:device error:NULL];
    // 2. 输出图像
    _imageOutput = [AVCaptureStillImageOutput new];
    // 3. 拍摄会话
    _captureSession = [AVCaptureSession new];
    // 4. 将输入／输出添加到拍摄会话
    // 为了避免因为客户手机的设备故障以及其他原因，通常需要判断设备能否添加到会话
    if (![_captureSession canAddInput:_inputDevice]) {
        NSLog(@"无法添加输入设备");
        return;
    }
    if (![_captureSession canAddOutput:_imageOutput]) {
        NSLog(@"无法添加输出设备");
        return;
    }
    [_captureSession addInput:_inputDevice];
    [_captureSession addOutput:_imageOutput];
    // 5. 设置预览图层
    _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
    // 指定图层的大小 - 模态展现的，在 viewDidLoad 方法中，视图的大小还没有确定
    CGRect rect = [UIScreen mainScreen].bounds;
    rect.size.height -= 130;
    _previewLayer.frame = rect;
    [_previewView.layer insertSublayer:_previewLayer atIndex:0];
//    [_previewView.layer addSublayer:_previewLayer];
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self startCapture];
}
- (void)startCapture {
    [_captureSession startRunning];
}
- (void)stopCapture {
    [_captureSession stopRunning];
}
- (void)capturePicture {
    AVCaptureConnection *conn = _imageOutput.connections.firstObject;
    if (conn == nil) {
        NSLog(@"没有连接到摄像头");
        return;
    }
    [_imageOutput captureStillImageAsynchronouslyFromConnection:conn completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == nil) {
            NSLog(@"没有图像采样缓冲区");
            return;
        }
        NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:data];
        // 将图像的上下两部分不显示在预览图层中的内容裁切掉！
        CGRect rect = self.previewView.bounds;
        // 2> 计算裁切掉的大小
        CGFloat offset = (self.view.bounds.size.height - rect.size.height) * 0.5;
        UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
        [image drawInRect:CGRectInset(rect, 0, -offset)];
        [self.waterprintImage.image drawInRect:self.waterprintImage.frame];
        [self.waterprintLabel.attributedText drawInRect:self.waterprintLabel.frame];
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndPDFContext();
        UIImageWriteToSavedPhotosAlbum(result, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }];
    
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = (error == nil) ? @"照片保存成功" : @"照片保存失败";
    _tipLabel.text = msg;
    [self stopCapture];
    double duration = 1.0;
    [UIView animateWithDuration:duration delay:YJQCameraPictureDuration options:0 animations:^{
        _tipLabel.alpha = 1.0;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:duration animations:^{
            _tipLabel.alpha = 0;
        }];
    }];
    _capturedPicture = image;
}
/**
切换摄像头

@return 如果 _inputDevice 有值，要根据对应的摄像头对调，如果没有值，返回后置摄像头
*/
- (AVCaptureDevice *)captureDevice {
    //获取当前的镜头位置
    AVCaptureDevicePosition position = _inputDevice.device.position;
    position = (position != AVCaptureDevicePositionBack) ? AVCaptureDevicePositionBack : AVCaptureDevicePositionFront;
    // 2. 具体的设备 - 摄像头／麦克风(模拟器没有摄像头，应该使用真机测试)
    // 返回摄像头的数组，前置／后置
    NSArray *array = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    AVCaptureDevice *device;
    for (AVCaptureDevice *obj in array) {
        if (obj.position == position) {
            device = obj;
            break;
        }
    }
    return device;
}

@end
